package com.my.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/5 15:57
 */

// 创建资源类，定义属性和操作方法
class Share{
    private int number = 0;
    
    // 创建Lock
    private ReentrantLock lock = new ReentrantLock();
    
    // 创建Condition 记录当前锁的状态
    private Condition condition = lock.newCondition();
    
    
    // 生产者
    public void incr() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + " :: " + number);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
    // 消费者
    
    public void decr() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + " :: " + number);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}

public class ThreadDemo2 {

    public static void main(String[] args) {
        Share share = new Share();
        // 生产者
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "AA").start();
        
        // 消费者
        new Thread(() -> {
            for (int i = 0; i < 10; i++){
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "CC").start();

        // 消费者
        new Thread(() -> {
            for (int i = 0; i < 10; i++){
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "DD").start();
    }
    
}
